package org.zh.home.controller;

import javax.inject.Inject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zh.home.entity.Group;
import org.zh.home.model.AjaxMsg;
import org.zh.home.model.Pager;
import org.zh.home.model.SystemConstants;
import org.zh.home.service.IGroupService;

@Controller
@RequestMapping("/admin/group")
public class GroupController {
	private IGroupService groupService;
	
	public IGroupService getGroupService() {
		return groupService;
	}

	@Inject
	public void setGroupService(IGroupService groupService) {
		this.groupService = groupService;
	}
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public String group() {
		return "group/list";
	}
	
	@RequestMapping(value="/list",method=RequestMethod.POST)
	public @ResponseBody Pager<Group> group(String name) {
		return groupService.find(name);
	}
	
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String add() {
		return "group/add";
	}
	
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public String add(Group group,String columns) {
		groupService.add(group, columns);
		return SystemConstants.CLOSE_SCRIPT;
	}
	@RequestMapping(value="/update/{id}",method=RequestMethod.GET)
	public String update(@PathVariable int id,Model model) {
		Group group = groupService.load(id);
		String url = "";
		if(group!= null) {
			model.addAttribute("group",group);
			url = "group/update";
			//还需要获取分组能管理的栏目
		} else {
			url = "group/add";
		}
		return url;
	}
	
	@RequestMapping(value="/update/{id}",method=RequestMethod.POST)
	public String update(@PathVariable int id,Group group,String columns) {
		groupService.update(group, columns);
		return SystemConstants.CLOSE_SCRIPT;
	}
	
	@RequestMapping("/delete/{id}")
	public @ResponseBody AjaxMsg delete(@PathVariable int id) {
		AjaxMsg msg = new AjaxMsg();
		try {
			groupService.delete(id);
			msg.setSuccess(true);
			msg.setMsg("删除分组成功");
		} catch (Exception e) {
			msg.setSuccess(false);
			msg.setMsg(e.getMessage());
		}
		return msg;
	}
}
